package com.springboot.config.exception;
import com.springboot.config.tool.Tip;
import com.springboot.config.tool.ToolUtil;
import com.springboot.project.common.entity.Log;
import com.springboot.project.common.entity.User;
import com.springboot.project.common.service.impl.LogServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 全局的的异常拦截器（拦截所有的控制器）（带有@RequestMapping注解的方法上都会拦截）
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private LogServiceImpl logService;

    /**
     * 拦截业务异常
     */
    @ExceptionHandler(BussinessException.class)
    @ResponseBody
    public Tip bussinessExceptionHandler(BussinessException e,HttpServletRequest request) {
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Log log = new Log();
        if(user != null)
        {
            log.setUserId((long)(user.getId()));
            log.setUsername(user.getUsername());
        }
        log.setOperation("error");
        log.setMethod(request.getRequestURL().toString());
        log.setCreateTime(new Date());
        log.setDetail(e.getMessage());
        log.setType(2);
        log.setTime(0);
        log.setIp(ToolUtil.getIpAddr(request));
        logService.insert(log);
        logger.error(e.getMessage(), e);
        return new Tip(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public Object allExceptionHandler(HttpServletRequest request,Exception exception) {
        User user = (User) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Log log = new Log();
        if (user != null)
        {
            log.setUserId((long)(user.getId()));
            log.setUsername(user.getUsername());
        }
        log.setOperation("error");
        log.setMethod(request.getRequestURL().toString());
        log.setCreateTime(new Date());
        log.setDetail(exception.getMessage());
        log.setType(2);
        log.setTime(0);
        log.setIp(ToolUtil.getIpAddr(request));
        logService.insert(log);
        logger.error(exception.getMessage(), exception);
        return new ModelAndView("500");
    }
}
